import React, { useEffect, useState } from 'react';
import { Button, Input, Tabs, Table, Pagination, Divider, Badge } from 'antd';
import styles from './SMSquotaList.less';
import tableFilter from '../../../components/tableFilter';
import { quotaList, ownerDept } from '../services/quotaApi';
import SMSconfigModal from './components/SMSconfigModal';

const { TabPane } = Tabs;

function SMSquotaPage(props) {
  const { getColumnSearchProps = () => {}, history } = props;
  // 查询状态
  const [searchValue, updateSearchValue] = useState();
  const [filters, updateFilters] = useState({});
  const [radioValue, updateRadioValue] = useState(1);
  const [currentPage, updatePage] = useState(1);
  const [currentPageSize, updatePageSize] = useState(10);
  const [listData, updateListData] = useState([]);

  // 纯交互状态
  const [inputValue, updateInputValue] = useState();
  const [loading, updateLoading] = useState(false);
  const [modalVisible, updateModalVisible] = useState(false);

  // 数据状态
  const [messDeptList, updateMessDeptList] = useState([]);
  const [total, updateTotal] = useState(0);

  const getValueFormFilters = propertyOfFilters => {
    if (filters) {
      const arr = filters[propertyOfFilters];
      if (arr && arr.length > 0) {
        return arr;
      }
      return [];
    }
    return [];
  };

  // 请求
  const fetchList = async () => {
    // 请求列表数据
    updateLoading(true);
    const newparams = {
      effectiveStatus: radioValue,
      selfQueryParam: searchValue,
      auditStatus: getValueFormFilters('auditStatus')[0],
      quotaType: getValueFormFilters('smsQuota.quotaType')[0],
      orgCode: getValueFormFilters('ownerDeptName')[0],
      pageNum: currentPage,
      pageSize: currentPageSize
    };
    const { errCode, datas, totalCount } = await quotaList(newparams);
    updateLoading(false);
    if (errCode === 0) {
      updateListData(datas);
      updateTotal(totalCount);
    } else {
      updateListData([]);
      updateTotal(0);
    }
  };

  const fetchOrgList = async () => {
    // 请求此部门层级下的归属部门数据
    updateLoading(true);
    const orgParam = {
      effectiveStatus: radioValue,
      selfQueryParam: searchValue,
      auditStatus: getValueFormFilters('auditStatus')[0],
      quotaType: getValueFormFilters('smsQuota.quotaType')[0]
    };
    const { errCode, datas } = await ownerDept(orgParam);
    updateLoading(false);
    if (errCode === 0) {
      const deptFilter = (datas || []).map(item => ({
        text: item.ownerDeptName,
        value: item.ownerDept
      }));
      updateMessDeptList(deptFilter);
    } else {
      // 查询失败，清空归属部门
      updateMessDeptList([]);
    }
  };

  // 监听状态变更，更新表格内容
  useEffect(() => {
    fetchList();
  }, [radioValue, filters, currentPage, currentPageSize, searchValue]);

  // 监听、根据，输入框状态、发布状态，更新归属部门
  useEffect(() => {
    fetchOrgList();
  }, [
    radioValue,
    searchValue,
    getValueFormFilters('auditStatus')[0],
    getValueFormFilters('smsQuota.quotaType')[0]
  ]);

  const onRadioChange = activeKey => {
    updateRadioValue(+activeKey);
    updateFilters({});
    updatePage(1);
    updateSearchValue();
    updateInputValue();
  };

  // 默认值设置
  const onSetDefaultValueClick = () => {
    updateModalVisible(true);
  };

  const onUpdateInput = event => {
    updateInputValue(event.target.value);
  };

  const onInputSearch = () => {
    updateSearchValue(inputValue);
    updateFilters({});
    updatePage(1);
  };

  const onPageChange = _page => {
    updatePage(_page);
  };

  const onPageSizeChange = (_cur, _size) => {
    updatePageSize(_size);
    updatePage(1);
  };

  const render = text => (text ? <span title={text}>{text}</span> : '-');

  const columns = [
    {
      title: '消息源名称',
      dataIndex: 'msgSourceName',
      width: 150,
      render
    },
    {
      title: '渠道名称',
      dataIndex: 'pushChannelName',
      width: 150,
      render
    },
    {
      title: '归属部门',
      dataIndex: 'ownerDeptName',
      width: 150,
      ...getColumnSearchProps(messDeptList),
      filteredValue: getValueFormFilters('ownerDeptName') || [],
      render
    },
    {
      title: '管理员',
      dataIndex: 'owner',
      width: 100,
      render: text => {
        // 示例返回： "[{"key":"330211199504230049","name":"测试人员"}]"
        if (text && text !== 'null') {
          return render(
            JSON.parse(text)
              .map(item => item.name)
              .join(',')
          );
        }
        return '-';
      }
    },
    {
      title: '短信配额类型',
      dataIndex: 'smsQuota.quotaType',
      width: 150,
      // 1-年度 2-月度
      render: text => {
        let str = null;
        switch (text) {
          case 1: // 已发布
            str = '按年度';
            break;
          case 2: // 未发布
            str = '按月份';
            break;
          default:
            break;
        }
        return render(str);
      },
      filterMultiple: false,
      filters: [
        {
          text: '按年度',
          value: 1
        },
        {
          text: '按月份',
          value: 2
        }
      ],
      filteredValue: getValueFormFilters('smsQuota.quotaType')
    },
    {
      title: '短信配额',
      dataIndex: 'quotaCount',
      width: 100,
      render
    },
    {
      title: '当前使用配额',
      dataIndex: 'usedQuota',
      width: 100,
      render
    },
    {
      title: '续订总额',
      dataIndex: 'renewQuota',
      width: 100,
      render
    },
    {
      title: '发布状态',
      dataIndex: 'auditStatus',
      width: 100,
      // 0-待审批 -1-未通过 1-已发布 2-未发布
      render: text => {
        let config = {};
        switch (text) {
          case 1: // 已发布
            config = { color: 'green', text: '已发布' };
            break;
          case 2: // 未发布
            config = { status: 'default', text: '未发布' };
            break;
          case 0: // 待审批
            config = { color: 'blue', text: '待审批' };
            break;
          case -1: // 未通过
            config = { color: 'red', text: '未通过' };
            break;
          default:
            break;
        }
        return <Badge {...config} />;
      },
      filterMultiple: false,
      filters: [
        {
          text: '待审批',
          value: 0
        },
        {
          text: '未通过',
          value: -1
        },
        {
          text: '已发布',
          value: 1
        },
        {
          text: '未发布',
          value: 2
        }
      ],
      filteredValue: getValueFormFilters('auditStatus')
    },
    {
      title: '有效起始时间',
      width: 200,
      dataIndex: 'smsQuota.effectiveBeginTime',
      render
    },
    {
      title: '有效截止时间',
      width: 200,
      dataIndex: 'smsQuota.effectiveEndTime',
      render: text => {
        if (text === '2199-01-01 00:00:00') {
          return '永久';
        }
        return render(text);
      }
    },
    {
      title: '操作',
      width: 100,
      fixed: (listData || []).length > 0 ? 'right' : false,
      dataIndex: 'operation',
      render: (text, record) => (
        <div>
          <a
            disabled={radioValue !== 1}
            onClick={() => {
              history.push(
                `/messageCenter/SMSmanagement/SMSquotaList/AddSMSquota?msgSourceId=${record.msgSourceId}&effectiveStatus=${record.smsQuota.effectiveStatus}`
              );
            }}>
            配置
          </a>
          <Divider type='vertical' />
          <a
            onClick={() => {
              history.push(
                `/messageCenter/SMSmanagement/SMSquotaList/historyRecord?msgSourceId=${record.msgSourceId}`
              );
            }}>
            历史配额
          </a>
        </div>
      )
    }
  ];

  return (
    <div className={styles.root}>
      <div className={styles.topSearch}>
        <Tabs onChange={onRadioChange} value={radioValue} animated={false}>
          <TabPane key={1} tab='生效' />
          <TabPane key={2} tab='未生效' />
          <TabPane key={3} tab='失效' />
        </Tabs>
        <div>
          <Button
            onClick={onSetDefaultValueClick}
            type='primary'
            style={{
              marginRight: '8px'
            }}>
            默认值设置
          </Button>
          <Input.Search
            value={inputValue}
            placeholder='请输入消息源名称/渠道名称'
            onChange={onUpdateInput}
            onSearch={onInputSearch}
            style={{
              width: '285px'
            }}
          />
        </div>
      </div>
      <div className={styles.tableBox}>
        <Table
          columns={columns}
          dataSource={listData}
          pagination={false}
          loading={loading}
          className={`${listData.length === 0 ? styles.aaa : ''}`}
          rowKey='smsQuotaId'
          scroll={{ x: 1700 }}
          onChange={(pagination, _filters) => {
            const { ownerDeptName, ...other } = _filters;
            // "发布状态"筛选变更，更新"归属部门"选中值状态
            let newFilter = {
              ...filters,
              ...other
            };

            let newOwnerDept = ownerDeptName || [];

            if (
              other.auditStatus &&
              other.auditStatus[0] !== getValueFormFilters('auditStatus')[0]
            ) {
              newOwnerDept = [];
            }
            newFilter = {
              ...newFilter,
              ownerDeptName: newOwnerDept
            };
            updateFilters(newFilter);
            updatePage(1);
          }}
        />
      </div>
      <div
        style={{
          display: 'flex',
          justifyContent: 'flex-end',
          marginTop: '8px',
          marginBottom: '10px'
        }}>
        <Pagination
          current={currentPage}
          pageSize={currentPageSize}
          onChange={onPageChange}
          onShowSizeChange={onPageSizeChange}
          total={total}
          showQuickJumper
          showSizeChanger
          showTotal={_total => `共有${_total}条`}
        />
      </div>
      <SMSconfigModal
        visible={modalVisible}
        onCancel={() => {
          updateModalVisible(false);
        }}
      />
    </div>
  );
}

export default tableFilter(SMSquotaPage);
